package com.gec.teams.wechat.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.gec.teams.wechat.annotation.AuthAccess;
import com.gec.teams.wechat.common.ThreadLocalToken;
import com.gec.teams.wechat.mapper.StudentMapper;
import com.gec.teams.wechat.pojo.entity.MessageEntity;
import com.gec.teams.wechat.pojo.vo.*;
import com.gec.teams.wechat.service.MessageService;
import com.gec.teams.wechat.service.UserService;
import com.gec.teams.wechat.task.EmailTask;
import com.gec.teams.wechat.task.MessageTask;
import com.gec.teams.wechat.util.JwtUtil;
import com.gec.teams.wechat.util.R;
import com.gec.teams.wechat.exception.TeamsException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/14 9:14
 */
//添加跨域注解
//@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
@Api( value = "用户相关接口" ,tags = "测试用户接口")
public class UserController {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UserService userService;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplatel;

    @Autowired
    private EmailTask emailTask;
    @Autowired
    private JwtUtil jwtUtil;
    @Value("${teams.jwt.cache-expire}")
    private  int cacheExpire;
    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Autowired
    private MessageService messageService;

//    @AuthAccess
    @GetMapping("/test")
    @ApiOperation("测试方法")
    @RequiresPermissions(value = {"ROOT","USER:INSERT"},logical = Logical.OR)
    public R testStudent(){
//        if(true)
//        throw new TeamsException("测试异常",201);
//        String token = threadLocalToken.getToken();
//        return R.ok("测试方法来咯");
        return R.error(500,"错误方法");
    }


    @AuthAccess
    @PostMapping("/sayHello")
    @ApiOperation("最简单的测试方法") //Swagger声明方法添加@ApiOperation注解,(方法说明)
    public R sayHello(@Valid @RequestBody Test vo){
        return R.ok().put("msg", "Hello"+vo.getName());
    }

    @AuthAccess
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R register(@RequestBody RegisterFormVo registerFormVo){
        int id = userService.registerUser(registerFormVo.getRegisterCode()
                , registerFormVo.getCode(), registerFormVo.getNickname(), registerFormVo.getPhoto());
        //生成token
        String token = jwtUtil.createToken(id);
        //存进redis里面
        saveCacheToken(token,id);
        Set<String> permissions = userService.getsearchUserPermissions(id);
        threadLocalToken.setToken(token);
        return R.ok().put("permissions",permissions).put("token",token);
    }

    @AuthAccess
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public R login(@RequestBody LoginFormVo code){
        R r = new R().ok();
        UserDeptVo userDeptVo = userService.login(code.getCode());
        int id = userDeptVo.getId();
        String token = jwtUtil.createToken(id);
        r.put("token",token);
        saveCacheToken(token,id);
        Set<String> permissions = userService.getsearchUserPermissions(id);
        r.put("permissions",permissions);
        r.put("userName",userDeptVo.getName());
        r.put("photo",userDeptVo.getPhoto());
        r.put("deptName",userDeptVo.getDept().getDeptName());
        String date = new DateTime(userDeptVo.getHiredate()).toString("yyyy-MM-dd");
        r.put("date",date);
        //token也要存进redis里面
        saveCacheToken(token,id);
        threadLocalToken.setToken(token);
        return r;
    }

    @PostMapping("/searchMembers")
    @ApiOperation("查找成员")
    @RequiresPermissions(value = {"ROOT","MEETING:INSERT", "MEETING:UPDATE"} ,logical = Logical.OR)
    public R searchMembers(@Valid @RequestBody SearchMembersFormVo form){
        if(!JSONUtil.isJsonArray(form.getMembers())){
            throw new TeamsException("member不是JSON数组");
        }
        List  parm = JSONUtil.parseArray(form.getMembers()).toList(Integer.class);
        ArrayList list =userService.searchMembers(parm);
        return R.ok().put("result",list);

    }


    @PostMapping("/searchUserGroupByDept")
    @ApiOperation("查询员工列表，按照部门分组排列")
    @RequiresPermissions(value = {"ROOT","EMPLOYEE:SELECT"},logical = Logical.OR)
    public R searchUserGroupByDept(@Valid @RequestBody SearchUserGroupByDeptFormVo form){
        ArrayList<HashMap> list=userService.searchUserGroupByDept(form.getKeyword());
        return R.ok().put("result",list);
    }

    @GetMapping("/getIdByToken")
    @ApiOperation("根据ID删除会议")
    public R getIdByToken(@RequestHeader("token") String token){
        int userId = jwtUtil.getUserId(token);
        return R.ok().put("id",userId);
    }


    private void saveCacheToken(String token, int userId) {
        redisTemplatel.opsForValue().set(token,userId+"",cacheExpire);
    }

}
